package com.aizhixin.lab.remote;

import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.course.domain.ChapterImagesResultDTO;
import com.aizhixin.lab.course.course.dto.ChapterImagesDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@Slf4j
@Component
public class RDSClient {
    @Autowired
    private Config config;

    /*
    {
      "result": false,
      "code": 417,
      "cause": "虚拟机数量不在1-3范围内"
    }

    {
      "data": "5dad7a82e632e01b6bc6ed02",
      "result": true,
      "code": 200
    }
     */
    public ChapterImagesResultDTO saveVM(String token, ChapterImagesDTO dto) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", token);
        String queryPath = config.getRdsApiPath() + config.getRdsApiSaveVM();
        RestTemplate restTemplate = new RestTemplate();
        try {
            ObjectMapper mapper = new ObjectMapper();
            String inJson = mapper.writeValueAsString(dto);
            HttpEntity<byte[]> entity = new HttpEntity<>(inJson.getBytes(Charset.forName("UTF-8")), headers);
            ResponseEntity<ChapterImagesResultDTO> responseEntity = restTemplate.exchange(queryPath, HttpMethod.POST, entity, ChapterImagesResultDTO.class);
            ChapterImagesResultDTO domain = responseEntity.getBody();
            log.info("result:" + domain.getResult() + ",code:" + domain.getCode());
            return domain;
        } catch (Exception e) {
            log.warn("saveVM Exception", e);
            return null;
        }
    }
}
